package com.LeeCode;

/**
 * 合并零之间的节点
 */

public class Code2181 {
    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 3, 0, 2, 2, 0};
        ListNode head = Utils.arrayToListNode(nums);
        Utils.printListNode(new Code2181().mergeNodes(head));
    }

    public ListNode mergeNodes(ListNode head) {
        ListNode dummy = new ListNode(0), curr = dummy;
        head = head.next;
        int count = 0;
        while (head != null) {
            count += head.val;
            if (head.val == 0) {
                curr.next = new ListNode(count);
                curr = curr.next;
                count = 0;
            }
            head = head.next;
        }
        return dummy.next;
    }

    public ListNode mergeNodes1(ListNode head) {
        ListNode tail = head;
        for (ListNode cur = head.next; cur.next != null; cur = cur.next) {
            if (cur.val != 0) {
                tail.val += cur.val;
            } else {
                tail = tail.next;
                tail.val = 0;
            }
        }
        tail.next = null;
        return head;
    }
}
